package com.edu.juc.introduction.communication.lock;

import lombok.Data;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Data
public class Number {
    private Integer number = 0;

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() throws InterruptedException {
        lock.lock();
        try {
            // while 解决虚假唤醒问题
            while (number != 0)
                condition.await();
            number++;
            System.out.println(Thread.currentThread().getName() + ": " + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void sub() throws InterruptedException {
        lock.lock();
        try {
            // while 解决虚假唤醒问题
            while (number != 1)
                condition.await();
            number--;
            System.out.println(Thread.currentThread().getName() + ": " + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
